import tools from '@/tools'
import { log } from 'mathjs'

export default {
  state: {
    tags: tools.localRead('tags') ? JSON.parse(tools.localRead('tags')) : [],
    errors: tools.localRead('errors') ? JSON.parse(tools.localRead('errors')) : []
  },
  getters: {

  },
  mutations: {
    setTags (state, tags = []) {
      const list = JSON.stringify(tags)
      tools.localSave('tags', JSON.stringify(list))
      state.tags = tags
    },
    addTag (state, meta = {}) {
      const list = [...state.tags]
      let type = false
      list.map(item => {
        if (item.path === meta.path) type = true
      })
      if (type) return false
      list.push(meta)
      tools.localSave('tags', JSON.stringify(list))
      state.tags = list
    },
    closeTag (state, index = 0) {
      const list = [...state.tags]
      list.splice(index, 1)
      tools.localSave('tags', JSON.stringify(list))
      state.tags = list
    },
    closeTagByPath (state, path) {
      console.log(path,'path');
      const list = [...state.tags]
      list.forEach((item,index)=>{
        if (path && item.path===path) {
          list.splice(index, 1)
          tools.localSave('tags', JSON.stringify(list))
          state.tags = list
          const current = index === 0 ? index + 1 : index - 1
          const openItem = state.tags[current]
        }
      })
    },
    closeOther (state, meta = {}) {
      const list = []
      state.tags.map(item => {
        if (item.path === meta.path) {
          list.push(item)
        }
      })
      tools.localSave('tags', JSON.stringify(list))
      state.tags = list
    },
    setError (state, error = {}) {
      const list = [...state.errors]
      list.push(error)
      tools.localSave('errors', JSON.stringify(list))
      state.errors = list
    }
  },
  actions: {
    addErrorLog ({
      commit,
      rootState
    }, info) {
      // if (!window.location.href.includes('error_logger_page')) commit('setHasReadErrorLoggerStatus', false)
      const {
        user: {
          token,
          userId,
          username
        }
      } = rootState
      const data = {
        ...info,
        time: Date.parse(new Date()),
        token,
        userId,
        username
      }
      commit('setError', data)
    }
  }
}
